Caesar Cipher
Module 01 / Lesson 01
Visual Explanation
Theoretical Concept
The Caesar Cipher is a type of Substitution Cipher. It works by shifting each character of the message by a fixed number of positions (called the 'Key') in the alphabet.
Mathematical Rule:
Encryption: E(x) = (x + k) mod 26
Decryption: D(x) = (x - k) mod 26
Decryption: D(x) = (x - k) mod 26
For example, with a shift of 3, 'A' becomes 'D'. Despite its historical significance, it is very easy to break using brute force or frequency analysis.
Python Implementation
def caesar_cipher(text, shift, mode='encrypt'):
result = ""
if mode == 'decrypt':
shift = -shift
for char in text:
if char.isalpha():
start = ord('A') if char.isupper() else ord('a')
new_char = chr((ord(char) - start + shift) % 26 + start)
result += new_char
else:
result += char
return result
# Usage
msg = "CipherBoy"
encrypted = caesar_cipher(msg, 3, 'encrypt')
print(f"Encrypted: {encrypted}")